package com.net.web.server.task;

import com.net.common.entity.CacheBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import static com.net.web.server.config.ServerMapContext.cacheMap;

@Component
@Slf4j
public class CacheTask {

    @Scheduled(cron = "0 0/1 * * * ?")
    private void execute() {
        if (CollectionUtils.isEmpty(cacheMap)) {
            return;
        }

        int size = 0;
        Collection<Map<String, CacheBean>> values = cacheMap.values();
        for (Map<String, CacheBean> value : values) {
            Iterator<Map.Entry<String, CacheBean>> iterator = value.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, CacheBean> next = iterator.next();
                if (next.getValue().getExpirationTime().after(new Date())) {
                    continue;
                }
                iterator.remove();
                size++;
            }
        }

        if (size == 0) {
            return;
        }
        log.info("删除缓存key：{} 个", size);
    }
}
